#!/bin/bash
echo "开始k8s构建过程,准备deployment（pod）、service, k8s部署时从私有镜像仓库拉取镜像..."
# 公共路径（确保容器内存在）
common_path=/planet/programs/planet-devops-business-server
# shellcheck disable=SC2164
cd "$common_path"
cur_path=$(pwd)
echo "当前路径：$cur_path"

#################################### 公共变量 ############################################
app_name=${1:-"planet-devops-business-server"}
# 镜像tag
FINAL_IMAGE_TAG="latest"
# docker仓库用户名、密码
harbor_username=planet
harbor_password=planetAdmin@1998
harbor_addr=192.168.222.109:10010

################################### 删除旧的镜像和容器 ##########################################3
# 获得docker容器id和镜像id，查询 app_name容器信息，并获取列表第一个($1)参数

# shellcheck disable=SC2006
container_ids=`docker ps -a | grep "$app_name" | awk '{print $1 }'`
# shellcheck disable=SC2006
img_ids=`docker images | grep "$app_name" | awk '{print $3 }'`

# 如果容器正在运行，停止它
while IFS= read -r container_id; do
  # 获取容器状态
  status=$(docker inspect --format='{{.State.Status}}' "$container_id")
  # 这里也可以不用加状态判断，直接停止删除
  if [[ "$status" = "running" || "$status" = "restarting" ]]; then
    echo "Stopping $status container: $container_id"
    docker stop "$container_id"
    echo "Delete container: $container_id"
    docker rm -f "$container_id"
  fi
done <<< "$container_ids"

# 删除镜像
while IFS= read -r img_id; do
  echo "delete image: $img_id"
  docker rmi -f "$img_id"
done <<< "$img_ids"

##################################### 构建镜像并打tag,并推送到私有仓库 ##################################
## 登录仓库(如果是公有仓库的话不需要登录)
docker login -u "$harbor_username" -p "$harbor_password" "$harbor_addr"
echo "planet image registry login success ..."

echo "delete harbor registry old images ..."
CURRENT_DIGEST=$(docker inspect -f '{{index .RepoDigests 0}}' "$harbor_addr"/"$app_name"/"$app_name":"$FINAL_IMAGE_TAG")
# 提取 digest 值
DIGEST=$(echo "$CURRENT_DIGEST" | cut -d '@' -f 2)
docker manifest inspect "$harbor_addr"/"$app_name"/"$app_name":"$FINAL_IMAGE_TAG" > /dev/null 2>&1
# shellcheck disable=SC2181
if [ $? -eq 0 ]; then
  curl -X DELETE -u $harbor_username:$harbor_password $harbor_addr/api/v2.0/projects/"$app_name"/repositories/"$app_name"/artifacts/"$DIGEST"
else
  echo "Image does not exist in Harbor registry ..."
fi


## 打标签,参数解释：docker tag 源镜像名:版本号 镜像仓库地址(完整地址IP:PORT,80的话可省略)/目标仓库/目标镜像名:版本号
# 目标仓库名称和项目名称一致
docker build -t "$app_name":"$FINAL_IMAGE_TAG" --no-cache -f ./Dockerfile .
docker tag "$app_name":"$FINAL_IMAGE_TAG" "$harbor_addr"/"$app_name"/"$app_name":"$FINAL_IMAGE_TAG"

# 删除旧的镜像
#docker rmi -f "$harbor_addr"/"$app_name"/"$app_name":"$FINAL_IMAGE_TAG"

## 推送到镜像仓库(提前在镜像仓库创建名为app_name的仓库) 用户名/仓库名:版本号
docker push "$harbor_addr"/"$app_name"/"$app_name":"$FINAL_IMAGE_TAG"


############################ 使用 k8s构建,deployment，pod，service ###########################
# 定义Kubernetes配置文件路径
K8S_CONFIG_FILE="./planet-devops-deployment.yaml"
# 先删除原先的
kubectl delete -f "$K8S_CONFIG_FILE"
# 应用Kubernetes配置文件
kubectl apply -f "$K8S_CONFIG_FILE"
# 命名空间
K8S_NAMESPACE_NAME="planet-system"
# 配置文件中应用的标签
K8S_APP_LABEL="app=planet-devops-business-server"
# 配置文件中定义的service名称
K8S_SERVICE_NAME="planet-devops-business-server-service"

# 等待Pod启动并准备好接收请求
POD_NAME=$(kubectl get pods -n "$K8S_NAMESPACE_NAME" --selector "$K8S_APP_LABEL" -o jsonpath='{.items[0].metadata.name}')
echo "Waiting for Pod $POD_NAME to be ready..."
while [[ $(kubectl get pod "$POD_NAME" -n "$K8S_NAMESPACE_NAME" -o jsonpath='{.status.containerStatuses[0].ready}') != "true" ]]; do
  sleep 5
done

# 获取Service的外部IP和端口
EXTERNAL_IP=$(kubectl get svc "$K8S_SERVICE_NAME" -n "$K8S_NAMESPACE_NAME" -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
EXTERNAL_PORT=60001

# 输出外部访问地址和端口
echo "Application is now accessible at http://${EXTERNAL_IP}:${EXTERNAL_PORT}"
